/**
* The Footbar global namespace 
* @class Footbar.Plugins
* @static
*/
if (typeof Footbar == "undefined") {
 	Footbar = {};
}
//Ref:http://weblogs.mozillazine.org/weirdal/archives/008101.html
const objScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader);
Footbar.Plugins={			
		activeEngine:null,
		foundEngines : [],
		init:function(){
                var initPath=Footbar.Util.findPluginPath(true)+"chrome\\content\\Engines";
                this.loadEngines( initPath );
        },
		/**
		 * Return List of found engines
		 */
		getEngines:function(){
			return this.foundEngines;
		},
		
		/**
		 * Load all the
		 * @param {Object} initPath
		 */
		loadEngines: function(initPath) {

            var homeDir = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			homeDir.initWithPath( initPath );
				
			
				// file is the given directory (nsIFile)
			var entries = homeDir.directoryEntries;
			var array = [];
			var isFirstEngine=true;
			while(entries.hasMoreElements())
			{
			 var entry = entries.getNext();
		 	 entry.QueryInterface(Components.interfaces.nsIFile);
			 var path="";
			 path=entry.path;	 
			 if(path.indexOf("Engine")>-1 && path.indexOf(".js") >-1){	 	
				var singleFilename="";
				var splited=path.split("\\");
					singleFilename= splited[splited.length-1];
			  //  alert("Found Engine :"+path+"\n singleFilename="+singleFilename);
				//Using closures so we can allocate new scope object for each engine 		
				this.foundEngines.push(
						function(engineFilename){
							var scropeObject = new Object();
                            objScriptLoader.loadSubScript('chrome://footbar/content/Engines/'+engineFilename, scropeObject);
                            var Engine;
							    try{
									//Create and Initalize the Engine
									Engine = new scropeObject.EngineImpl();
									Engine.init();

                                }catch(e){
									alert(e);
								}				
							return Engine;
						}(singleFilename));
						
						
						if(isFirstEngine){
							this.setActiveEngine(this.foundEngines[0]);//First found is used as active engine
							isFirstEngine=false;
						}
			 }
			}//while

			return this.foundEngines;
		},
		
		getActiveEngine:function(){
			return this.activeEngine;
		},
		
		setActiveEngine:function(engine){			
			nsPreferences.setUnicharPref("trucoder.engine.id", engine.id);
			this.activeEngine=engine;
		}       
}